<template>
  <div class="clients-page">
    <div class="card">
      <div class="table-toolbar">
        <div class="toolbar-left">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增客户
          </el-button>
          <el-button type="danger" :disabled="!selectedIds.length" @click="handleBatchDelete">
            <el-icon><Delete /></el-icon>
            批量删除
          </el-button>
        </div>
        <div class="toolbar-right">
          <el-select
            v-model="searchForm.type"
            placeholder="客户类型"
            clearable
            style="width: 120px; margin-right: 10px"
            @change="handleSearch"
          >
            <el-option label="个人" value="individual" />
            <el-option label="企业" value="company" />
          </el-select>
          <el-select
            v-model="searchForm.status"
            placeholder="客户状态"
            clearable
            style="width: 120px; margin-right: 10px"
            @change="handleSearch"
          >
            <el-option label="正常" value="active" />
            <el-option label="停用" value="inactive" />
          </el-select>
          <el-input
            v-model="searchForm.keyword"
            placeholder="搜索客户名称、联系人"
            style="width: 200px"
            @keyup.enter="handleSearch"
          >
            <template #append>
              <el-button @click="handleSearch">
                <el-icon><Search /></el-icon>
              </el-button>
            </template>
          </el-input>
        </div>
      </div>

      <el-table
        v-loading="loading"
        :data="tableData"
        @selection-change="handleSelectionChange"
        stripe
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="clientName" label="客户名称" min-width="150" />
        <el-table-column prop="clientType" label="客户类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getClientTypeTag(row.clientType)">
              {{ getClientTypeText(row.clientType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="contactPerson" label="联系人" width="120" />
        <el-table-column prop="phone" label="联系电话" width="130" />
        <el-table-column prop="email" label="邮箱" width="180" show-overflow-tooltip />
        <el-table-column prop="industry" label="行业" width="120" />
        <el-table-column prop="address" label="地址" min-width="200" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '正常' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdTime" label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatDate(row.createdTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row)">查看</el-button>
            <el-button type="success" size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 客户表单对话框 -->
    <ClientForm
      v-model:visible="formVisible"
      :form-data="formData"
      @success="handleFormSuccess"
    />

    <!-- 客户详情对话框 -->
    <ClientDetail
      v-model:visible="detailVisible"
      :client-id="selectedClientId"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getClientList, deleteClient } from '@/api/client'
import { formatDate } from '@/utils'
import type { Client, Pagination } from '@/types'
import ClientForm from './components/ClientForm.vue'
import ClientDetail from './components/ClientDetail.vue'

const router = useRouter()

const loading = ref(false)
const selectedIds = ref<string[]>([])
const tableData = ref<Client[]>([])
const formVisible = ref(false)
const detailVisible = ref(false)
const formData = ref<Partial<Client>>({})
const selectedClientId = ref('')

const searchForm = reactive({
  keyword: '',
  type: '',
  status: ''
})

const pagination = reactive<Pagination>({
  current: 1,
  pageSize: 20,
  total: 0
})

// 获取客户类型文本
const getClientTypeText = (type: number) => {
  const typeMap: Record<number, string> = {
    1: '个人',
    2: '企业',
    3: '组织'
  }
  return typeMap[type] || '未知'
}

// 获取客户类型标签样式
const getClientTypeTag = (type: number) => {
  const tagMap: Record<number, string> = {
    1: 'primary',
    2: 'success',
    3: 'warning'
  }
  return tagMap[type] || 'info'
}

// 获取客户列表
const fetchClientList = async () => {
  try {
    loading.value = true
    const params = {
      page: pagination.current,
      size: pagination.pageSize,
      ...searchForm
    }
    
    const response = await getClientList(params)
    console.log(response)
    tableData.value = response.records
    pagination.total = response.total
  } catch (error) {
    ElMessage.error('获取客户列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchClientList()
}

// 选择变化
const handleSelectionChange = (selection: Client[]) => {
  selectedIds.value = selection.map(item => item.id)
}

// 新增客户
const handleAdd = () => {
  formData.value = {}
  formVisible.value = true
}

// 查看客户
const handleView = (row: Client) => {
  router.push(`/clients/detail/${row.id}`)
}

// 编辑客户
const handleEdit = (row: Client) => {
  formData.value = { ...row }
  formVisible.value = true
}

// 删除客户
const handleDelete = async (row: Client) => {
  try {
    await ElMessageBox.confirm(`确定要删除客户 "${row.clientName}" 吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await deleteClient(row.id.toString())
    ElMessage.success('删除成功')
    fetchClientList()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedIds.value.length} 个客户吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await Promise.all(selectedIds.value.map(id => deleteClient(id)))
    ElMessage.success('批量删除成功')
    fetchClientList()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败')
    }
  }
}

// 表单提交成功
const handleFormSuccess = () => {
  fetchClientList()
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.current = 1
  fetchClientList()
}

// 当前页变化
const handleCurrentChange = (page: number) => {
  pagination.current = page
  fetchClientList()
}

onMounted(() => {
  fetchClientList()
})
</script>

<style lang="scss" scoped>
.clients-page {
  .pagination {
    margin-top: 20px;
    text-align: right;
  }
}
</style>
